<template lang="">
  <div class="edit-password">
  
    <h3 >{{ $t('sheZ') }}</h3>
    <div style="max-width: 50%">
      <a-form
        :model="formState"
        name="validate_other"
        v-bind="formItemLayout"
        ref="formRef"
      >
        <a-form-item
          name="old_password"
          :label="$t('jiuM')"
          :rules="[{ required: true, message: '请输入旧密码' }]"
        >
          <a-input-password v-model:value="formState.old_password" :placeholder="$t('qing-8')" />
        </a-form-item>

        <a-form-item
          name="new_password"
          :label="$t('xinM')"
          :rules="[{ 
            required: true, message: '请输入8-16个字符组成的新密码',
            min: 8, message: '请输入8-16个字符组成的新密码',
           }]"
        >
          <a-input-password v-model:value="formState.new_password" :placeholder="$t('qing-9')" />
        </a-form-item>

        <a-form-item
          name="confirm_password"
          :label="$t('queR')"
          :rules="[{ 
            required: true, message: '请输入8-16个字符组成的确认密码',
            min: 8, message: '请输入8-16个字符组成的新密码',
          }]"
        >
          <a-input-password v-model:value="formState.confirm_password" :placeholder="$t('qing-10')" />
        </a-form-item>

        <a-form-item
          name="phone_number"
          :label="$t('shou-2')"
          :rules="[{ 
            required: true, message: '请输入11位有效手机号码',
            max: 11, message: '请输入11位有效手机号码'
          }]"
        >
          <a-input-group compact style="display: flex">
            <a-select v-model:value="mobilePhoneArea" size="large" style="width: 80px" :disabled="true">
              <a-select-option 
                v-for="(value, index) in countryCodes" 
                :value="value" 
                :key="'mobilePhoneArea' + index"
              >{{ value }}</a-select-option>
            </a-select>
            <a-input v-model:value="formState.phone_number" :placeholder="$t('qing-11')" size="large" :disabled="true" />
          </a-input-group>
        </a-form-item>


        <a-form-item
          name="verify_code"
          :label="$t('yanZ')"
          :rules="[{ 
            required: true, message: '请输入验证码',
            max: 5, message: '请输入5位有效验证码'
          }]"
        >
          <a-input v-model:value="formState.verify_code" :placeholder="$t('qing-3')" size="large">
            <template #addonAfter>
              <a-button size="large" :loading="sending" @click="handleSendSmsCode">{{ buttonText }}</a-button>
            </template>
          </a-input>
        </a-form-item>
      </a-form>

      <a-button type="primary" size="large" html-type="submit"  danger block style="margin-top: 10px" @click="onSubmit">{{ $t('baoC') }}</a-button>
    </div>
  </div>

</template>
<script setup lang="ts">
import { ref, defineProps, defineEmits, reactive, onBeforeMount, toRaw } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import { generateMd5, getMobilePhoneInfo, countryCodes } from '@/utils';
import { setLoginPassword } from '@/api/safety';
import { Modal, message } from 'ant-design-vue';
import { useCache } from '@/hooks/web/useCache';
import { useUserStore } from '@/stores/userInfo';
import { sendSMSCode } from '@/api/account';
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router';
const { t } = useI18n()
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};
const router = useRouter();
// ty = 1 是设置（修改）登录密码，ty = 2 是重置登录密码
const editType = ref<number>(1);
const sending = ref<boolean>(false);
const buttonText = ref<string>(t('faSo'));
const countdownSecond = 90;
const countDown = ref<number>(countdownSecond);
const hasDisabledSent = ref<boolean>(false);
const formRef = ref<FormInstance>();
const { user } = useUserStore();

const curPhoneNumber = computed(() => {
  const { phoneNumber } = getMobilePhoneInfo(user.phone_number || '');
  return phoneNumber || '';
})
const mobilePhoneArea = computed(() => {
  const { areaCode } = getMobilePhoneInfo(user.phone_number || '');
  return areaCode || '+86';
});

const formState = reactive<Record<string, any>>({
  old_password: '',
  new_password: '',
  confirm_password: '',
  phone_number: curPhoneNumber,
  verify_code: '',
});

watch(
  () => user,
  (newValue) => {
    // 未设置手机号码
    if (!newValue.phone_number) {
      Modal.confirm({
          title: t('tiSh-0'),
          content: "您尚未绑定手机号码，是否绑定手机号码",
          okText: t('haoD'),
          cancelText: t('quXi'),
          onOk() {
              router.push({ name: 'PersonalInformation' })
          }
      });
  }
  },
  {
    deep: true,
  }
)

const onFinish = (values: any) => {
  console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};
let timer: any = null;
const handleSendSmsCode = () => {
  if (!formState.phone_number) {
    // 手机号为空，提示用户
    message.warn(t('shou-3'));
    return
  }
  
  if (hasDisabledSent.value) {
    return;
  }

  // 请求验证码
  sending.value = true
  sendSMSCode({phone_number: mobilePhoneArea.value + formState.phone_number })
  .then(() => {
    buttonText.value = t('count', [countDown.value])
    timer= setInterval(() => {
      countDown.value = countDown.value - 1
      buttonText.value = t('count-0', [countDown.value])

      if (countDown.value <= 0) {
        clearInterval(timer)
        hasDisabledSent.value = false
        buttonText.value = t('faSo-0')
        countDown.value = countdownSecond;
      }
    }, 1000)
  }).catch((e: any) => {
    console.log(e);
    clearInterval(timer);
  }).finally(() => {
    sending.value = false
    hasDisabledSent.value = true;
  })
}

const onSubmit = () => {
  if (!formRef.value) return;

  formRef.value
  .validate()
  .then(() => {
    console.log('submit!', toRaw(formState));
    fetchUpdatePwd();
  })
  .catch(error => {
    console.log('error', error);
  });
};
const resetForm = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
};
function logout() {
  const { wsCache } = useCache()
  wsCache.clear()
}
const fetchUpdatePwd = () => {
  const data = {
		...formState,
		old_password: generateMd5(formState.old_password),
		new_password: generateMd5(formState.new_password),
		confirm_password: generateMd5(formState.confirm_password),
    phone_number: mobilePhoneArea.value + formState.phone_number,
    verify_code: formState.verify_code,
    ty: editType.value
	}
  setLoginPassword(data)
  .then((data: any) => {
		if (data.status === "OK") {
			message.success(t('xiuG'));
      // 重置表单内容
      resetForm();
      logout();
      location.reload();
		}
  })
}
</script>
<style lang="less">
.edit-password {
  .ant-input-group-addon {
    padding: 0;
    background-color: transparent;
    border: none;
  }
}
</style>